import json
from time import sleep
from lxml import etree
from redis import ConnectionPool, StrictRedis
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

class RedisClient(object):
    pool = ConnectionPool(**{
        'host': '39.105.230.139',
        'port': 6379,
        'db': 0,
        'password': 950218
    })
    client = StrictRedis(connection_pool=pool)

    def set_cookies(self, cookies):
        self.client.set('cookies',cookies)

    def get_cookies(self):
        return self.client.get('cookies')

class SaveCookie(object):
    url = 'http://www.baidu.com'
    r = RedisClient()

    def SaveCookie(self):
        chrome_options = Options()
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--headless')
        driver = webdriver.Chrome(options=chrome_options)
        driver.set_window_size(1920, 1080)
        try:
            driver.get(self.url)
            driver.find_element_by_id('kw').send_keys("测试测试测试测试")
            driver.find_element_by_id('su').click()
            sleep(2)
            dictCookies = driver.get_cookies()
            jsonCookies = json.dumps(dictCookies)
            self.r.set_cookies(jsonCookies)
            print(driver.current_url)
            driver.quit()
        except:
            driver.quit()



if __name__ == '__main__':
    bot = SaveCookie()
    while True:
        bot.SaveCookie()
        print('休眠5秒')
        sleep(5)